/*
*  Copyright 2019-2025 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import me.zhengjie.modules.poker.PokerFormatUtil;
import me.zhengjie.modules.system.domain.AutoPokerActivateConfig;
import me.zhengjie.modules.system.domain.PokerActivateAwardInfo;
import me.zhengjie.modules.system.domain.PokerActivateInfo;
import me.zhengjie.modules.system.domain.PokerServer;
import me.zhengjie.modules.system.domain.dto.RankAward;
import me.zhengjie.modules.system.service.PokerActivateAwardInfoService;
import me.zhengjie.modules.system.service.PokerActivateInfoService;
import me.zhengjie.modules.system.service.PokerServerService;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import me.zhengjie.modules.system.service.AutoPokerActivateConfigService;
import me.zhengjie.modules.system.domain.dto.AutoPokerActivateConfigQueryCriteria;
import me.zhengjie.modules.system.mapper.AutoPokerActivateConfigMapper;
import org.bouncycastle.pqc.math.linearalgebra.RandUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import me.zhengjie.utils.PageUtil;

import java.sql.Timestamp;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.*;
import java.io.IOException;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import me.zhengjie.utils.PageResult;

/**
* @description 服务实现
* @author greazy
* @date 2025-06-26
**/
@Service
@RequiredArgsConstructor
public class AutoPokerActivateConfigServiceImpl extends ServiceImpl<AutoPokerActivateConfigMapper, AutoPokerActivateConfig> implements AutoPokerActivateConfigService {

    private final AutoPokerActivateConfigMapper autoPokerActivateConfigMapper;

    @Autowired
    PokerActivateInfoService pokerActivateInfoService;

    @Autowired
    PokerServerService pokerServerService;

    @Autowired
    PokerActivateAwardInfoService awardInfoService;

    @Override
    public PageResult<AutoPokerActivateConfig> queryAll(AutoPokerActivateConfigQueryCriteria criteria, Page<Object> page){
        return PageUtil.toPage(autoPokerActivateConfigMapper.findAll(criteria, page));
    }

    @Override
    public List<AutoPokerActivateConfig> queryAll(AutoPokerActivateConfigQueryCriteria criteria){
        return autoPokerActivateConfigMapper.findAll(criteria);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(AutoPokerActivateConfig resources) {
        autoPokerActivateConfigMapper.insert(resources);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(AutoPokerActivateConfig resources) {
        AutoPokerActivateConfig autoPokerActivateConfig = getById(resources.getId());
        autoPokerActivateConfig.copy(resources);
        autoPokerActivateConfigMapper.updateById(autoPokerActivateConfig);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteAll(List<Integer> ids) {
        autoPokerActivateConfigMapper.deleteBatchIds(ids);
    }

    @Override
    public void download(List<AutoPokerActivateConfig> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (AutoPokerActivateConfig autoPokerActivateConfig : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("活动名称", autoPokerActivateConfig.getName());
            map.put("0 扑克 1国王排名", autoPokerActivateConfig.getActivateType());
            map.put(" pubPoker1",  autoPokerActivateConfig.getPubPoker1());
            map.put(" pubPoker2",  autoPokerActivateConfig.getPubPoker2());
            map.put("换牌所需基础筹码数量", autoPokerActivateConfig.getChangePokerBaseNum());
            map.put("每次换牌需要增加筹码数量", autoPokerActivateConfig.getChangePokerAddNum());
            map.put("免费换牌次数", autoPokerActivateConfig.getActiveFreeChage());
            map.put("最大换牌次数", autoPokerActivateConfig.getActiveMaxChage());
            map.put("特殊物品", autoPokerActivateConfig.getSpecialGoodid());
            map.put("启用状态", autoPokerActivateConfig.getRunStatus());
            map.put("服务器标识", autoPokerActivateConfig.getServerIds());
            map.put("任务流水号", autoPokerActivateConfig.getTaskId());
            map.put(" activateDesc",  autoPokerActivateConfig.getActivateDesc());
            map.put("活动奖励", autoPokerActivateConfig.getAwardContent());
            map.put("活动截止时间", autoPokerActivateConfig.getEndTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public void autoGenPokerActivate() {
        AutoPokerActivateConfig activateConfig = this.getById(1);
        if (activateConfig.getRunStatus()==1){
            List<PokerServer> serverList = pokerServerService.list();
            List<Integer> genServerIds = Arrays.stream(activateConfig.getServerIds().split(","))
                    .map(Integer::parseInt)
                    .toList();
            for (PokerServer pokerServer : serverList) {
                if (genServerIds.contains(pokerServer.getId())){
                    PokerActivateInfo pokerActivateInfo = new PokerActivateInfo();
                    activateConfig.setId(null);
                    activateConfig.setTaskId(null);
                    BeanUtil.copyProperties(activateConfig,pokerActivateInfo,true);
                    pokerActivateInfo.setName(pokerActivateInfo.getName()+ DateUtil.today());
                    pokerActivateInfo.setActivateType(0);
                    pokerActivateInfo.setServerId(String.valueOf(pokerServer.getId()));
                    pokerActivateInfo.setPubPoker1(PokerFormatUtil.getRandomCard());
                    pokerActivateInfo.setPubPoker2(PokerFormatUtil.getRandomCard());
                    //结束时间
                    // 获取当前日期 + 设置时间为 23:55:00
                    LocalDateTime ldt = LocalDateTime.of(LocalDate.now(), LocalTime.of(23, 55));
                    Timestamp timestamp = Timestamp.valueOf(ldt);
                    pokerActivateInfo.setEndTime(timestamp);
                    //
                    String taskid = RandomUtil.randomStringUpper(15);
                    pokerActivateInfo.setTaskId(taskid);
                    pokerActivateInfo.setRunStatus(1);
                    pokerActivateInfoService.save(pokerActivateInfo);
                    //解析奖励，并入库保存
                    List<RankAward> awardList = JSONUtil.toList(JSONUtil.parseArray(activateConfig.getAwardContent()), RankAward.class);
                    for (RankAward rankAward : awardList) {
                        PokerActivateAwardInfo pokerActivateAwardInfo = new PokerActivateAwardInfo();
                        pokerActivateAwardInfo.setActivateId(String.valueOf(pokerActivateInfo.getId()));
                        pokerActivateAwardInfo.setRank(rankAward.getRank());
                        pokerActivateAwardInfo.setAwardContent(JSONUtil.toJsonStr(rankAward.getContent()).replace("goodName","name"));
                        awardInfoService.save(pokerActivateAwardInfo);
                    }
                }

            }
        }
    }
}